<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">地区目标</div>
      </div>
      <div class="p-cont">
        <div class="opr">
          <div class="opr-left">
            <el-button type="primary" @click="createNewDist"
              >新建目标</el-button
            >
          </div>
        </div>
        <div class="table-wrap">
          <el-table :data="distList" style="width: 100%" stripe>
            <el-table-column label="地区">
              <template #default="scope">
                {{ formatDist(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="healthEducationCount" label="健康教育" />
            <el-table-column
              prop="medicationManagementCount"
              label="用药管理"
            />
            <el-table-column prop="illnessInsuranceCount" label="大病保障" />
            <el-table-column fixed="right" label="操作" width="200">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="changDist(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="deleteDist(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="del-btn">
          <!-- <div class="del-left">
            <el-button type="primary" @click="plDeleteDrugs"
              >批量删除</el-button
            >
          </div> -->
          <div class="del-right">
            <myPagination
              :total="listNum || 0"
              @currentChange="currentChange"
              ref="myPaginationRef"
            />
          </div>
        </div>
        <!-- <div class="page">
          <div class="page-left">共{{ listNum }}条数据</div>
        </div> -->
      </div>

      <el-dialog v-model="dialogVisible" title="新建/编辑目标">
        <div class="dialog-adddrug">
          <el-form
            :model="form"
            label-width="120px"
            ref="ruleFormRef"
            :rules="rules"
          >
            <el-form-item label="地区" prop="area">
              <myDestSelect ref="destSelectRef" @destChange="destChange" />
            </el-form-item>
            <el-form-item label="健康教育" prop="healthEducationCount">
              <el-input
                v-model.number="form.healthEducationCount"
                placeholder="请输入健康教育目标人数"
              />
            </el-form-item>
            <el-form-item label="用药管理" prop="medicationManagementCount">
              <el-input
                v-model.number="form.medicationManagementCount"
                placeholder="请输入用药管理目标人数"
              />
            </el-form-item>
            <el-form-item label="大病保障" prop="illnessInsuranceCount">
              <el-input
                v-model.number="form.illnessInsuranceCount"
                placeholder="请输入大病保障目标人数"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetSubmit" v-if="editType === 'new'"
                >重置表单</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";

import myPagination from "@/components/myPagination.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { globalDataStoreHook } from "@/store/modules/globalData";
import {
  getDistrictGoals,
  createDistrictGoals,
  deleteDistrictGoals
} from "@/api/system";
import myDestSelect from "@/components/myDestSelect.vue";
const userStore = useUserStoreHook();
const destSelectRef = ref(null);
const listNum = ref(0);
const myPaginationRef = ref();
const distList = ref([]);
const userId = useUserStoreHook().userInfo.user;
const dialogVisible = ref(false);
const ruleFormRef = ref();
const form = ref({
  id: "",
  provinceId: "",
  cityId: "",
  areaId: "",
  healthEducationCount: 0, //健康教育目标人数
  medicationManagementCount: 0, //用药管理目标人数
  illnessInsuranceCount: 0 //大病
});
const editType = ref<"new" | "edit">("new");

const rules: any = reactive({
  healthEducationCount: [
    { type: "number", message: "健康教育目标人数大于等于0", min: 0 }
  ],
  medicationManagementCount: [
    { type: "number", message: "用药管理目标人数大于等于0", min: 0 }
  ],
  illnessInsuranceCount: [
    { type: "number", message: "大病保障目标人数大于等于0", min: 0 }
  ]
});

function destChange(value) {
  console.log("value:", value);
}

function currentChange() {
  getDistApi();
}
function changDist(data) {
  dialogVisible.value = true;
  editType.value = "edit";
  form.value = data;
  setTimeout(() => {
    destSelectRef.value.setDestValue(
      data.areaId || data.cityName || data.provinceId
    );
  }, 0);
}

function createNewDist() {
  editType.value = "new";
  dialogVisible.value = true;
  resetSubmit();
}

async function getDistApi() {
  const listRes = await getDistrictGoals({
    skip:
      (myPaginationRef.value.currentPage - 1) *
      myPaginationRef.value.curPageSize,
    limit: myPaginationRef.value.curPageSize
  });
  distList.value = listRes.list;
  if (myPaginationRef.value.currentPage === 1) {
    listNum.value = listRes.total;
  }
}

function deleteDist(dist) {
  ElMessageBox.alert(`确定要删除"${formatDist(dist)}"吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(async () => {
    await deleteDistrictGoals(dist.id, { userId });
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    await getDistApi();
  });
  return;
}

function formatDist(areaObj) {
  let temp = areaObj.provinceName;
  if (areaObj.cityName) {
    temp += "-" + areaObj.cityName;
  }

  if (areaObj.areaName) {
    temp += "-" + areaObj.areaName;
  }
  return temp;
}

function submitForm() {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const tempForm = Object.assign({}, form.value);
        const selectedObj = destSelectRef.value.userSelectedRegions;
        tempForm.provinceId = selectedObj.provinceId;
        tempForm.cityId = selectedObj.cityId;
        tempForm.areaId = selectedObj.areaId;
        if (editType.value === "new") {
          delete tempForm.id;
        }
        const tip = editType.value === "new" ? "新增" : "编辑";
        try {
          const res = await createDistrictGoals({
            userId: userStore.userInfo.user,
            data: JSON.stringify(tempForm)
          });
          if (!res || res.code === 0) {
            ElMessage({
              message: tip + "成功",
              type: "success"
            });
            resetSubmit();
          }
          dialogVisible.value = false;
          getDistApi();
        } catch (error) {
          ElMessage({
            message: tip + "失败," + JSON.stringify(error),
            type: "error"
          });
        }
      }
    });
  }
}

function resetSubmit() {
  form.value = {
    id: "",
    provinceId: "",
    cityId: "",
    areaId: "",
    healthEducationCount: 0, //健康教育目标人数
    medicationManagementCount: 0, //用药管理目标人数
    illnessInsuranceCount: 0 //大病
  };
}

onMounted(async () => {
  await getDistApi();
});
</script>
<style scoped lang="scss">
::v-deep(.el-backtop) {
  display: none !important;
}

.main {
  .part {
    .p-title {
      justify-content: flex-start;
    }
  }
}

.opr {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opr-right {
    width: 300px;
  }
}

.table-wrap {
  margin-top: 20px;
}

.del-btn {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .page-left {
    color: #bbb;
  }
}

.dialog-adddrug {
  width: 400px;

  .dist-row {
    display: flex;
    align-items: center;

    .dist-btn {
      margin: 0px 10px 10px 0px;
    }
  }
}
</style>
